package org.example;

import java.util.Random;

class Solution {
    public static int findKthLargest(int[] nums, int k) {
        return quickSort(nums, 0, nums.length - 1, k);
    }
    public static int quickSort(int[] nums, int l, int r,int k){
        if(l == r) return nums[l];
        //选择基准元素
        int key = nums[new Random().nextInt(r - l + 1) + l];
        //三路划分
        int left = l - 1, right = r + 1, i = l;
        while(i < right){
            if(nums[i] < key) swap(nums, ++left, i++);
            else if(nums[i] == key) i++;
            else swap(nums, --right, i);
        }
        //分类讨论
        //以下分为三个区间,长度分别为a个、b个、c个
        //[l, left] [left + 1, right - 1] [right, r]

        //计算中间区间和第三个区间的元素个数
        int c = r - right + 1, b = right - left - 1;
        //第k大元素处于第三个区域
        if(c >= k) return quickSort(nums, right, r, k);
            //第k大元素处于中间区域
        else if(b + c >= k) return key;
            //处于第一个区域
        else  return quickSort(nums, l, left, k - b - c);
    }
    private static void swap(int[] nums, int i, int j){
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
}
